package com.sse.product.rbac.service.impl;

import com.sse.product.rbac.entity.Menus;
import com.sse.product.exception.BizRuntimeException;
import com.sse.product.rbac.mapper.MenusMapper;
import com.sse.product.rbac.service.IMenusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author junyongli
 * @since 2022-07-22
 */
@Service
public class MenusServiceImpl implements IMenusService {

    @Autowired
    private MenusMapper menusMapper;

    @Override
    public List<Menus> listByIds(List<Long> menuIds) {
        return menusMapper.selectBatchIds(menuIds);
    }

    @Override
    public List<Menus> queryAll() {
        return menusMapper.selectList(null);
    }

    @Override
    @Transactional
    public Integer addMenu(Menus menus) {
        List<Menus> repeat = menusMapper.listByUniqueName(menus.getUniqueName());
        if (!CollectionUtils.isEmpty(repeat))
            throw new BizRuntimeException("菜单的名称(uniqueName)不能为重复!");
        return menusMapper.insert(menus);
    }

    @Override
    @Transactional
    public Integer updateMenu(Menus menus) {
        if (StringUtils.hasText(menus.getUniqueName())) {
            List<Menus> repeat = menusMapper.listByUniqueName(menus.getUniqueName());
            if (!CollectionUtils.isEmpty(repeat) && repeat.stream().anyMatch(item -> !item.getId().equals(menus.getId())))
                throw new BizRuntimeException("菜单的名称(uniqueName)不能为重复!");
        }
        Menus menu = menusMapper.selectById(menus.getId());
        if (Objects.isNull(menu))
            throw new BizRuntimeException("根据菜单ID无法查到菜单");
        return menusMapper.updateById(menus);
    }

    @Override
    @Transactional
    public Integer delMenu(Menus menus) {
        return menusMapper.deleteById(menus);
    }
}
